class Imager {
    constructor(imgPath = './imgs/phonePhoto.jpg',
                distance = 40,) {
        this.ele = new Image();
        this.ele.style.backgroundColor = '#' + [...new Array(3).keys()].map((n,index)=>{ //如果图片从网络获取，并且图片还没下载下来的情况下该背景色会开始渐变;
            return ['a','b','c','d','e','f'][Math.floor(Math.random(6)*6)]
        }).join('');
        // this.ele.style.width = '200px';
        this.ele.style.height = `${Math.round(Math.random() * 100 + 300)}px`;
        this.imgPath = imgPath;
        this.distance = distance;
        this.timer = null;
    }

    setOpacityZero() {
        this.ele.style.opacity = 0;
    }

    setOpacity1() { //这个暂时没用，但暂时保留
        this.ele.style.opacity = 1;
    }

    assignSrc() {
        this.ele.src = this.imgPath;
    }

    init() {
        this.setOpacityZero();
        this.assignSrc();
    }

    graduallyDisplay() {
        if (this.ele.style.opacity >= 1) {
            this.ele.style.opacity = 1;
            window.clearInterval(this.timer);
        } else {
            this.ele.style.opacity = Number(this.ele.style.opacity) + 0.01;
        }
    }

    graduallyWakeIfMust(screenOffsetTop) {
        const bodyOffsetHeight = document.body.offsetHeight;
        const bodyClientHeight = document.body.clientHeight;
        const mustInitedOffsetHeight = bodyOffsetHeight + bodyClientHeight + this.distance;
        this.timer = window.setInterval(() => {
            if (this.ele.scrollTop <= mustInitedOffsetHeight) {
                this.graduallyDisplay();
            }
        }, 17)
    }
}

class Uler {
    constructor(imgPathAry = [
        './imgs/0.jpg', './imgs/1.jpg', './imgs/2.jpg', './imgs/3.jpg', './imgs/4.jpg', './imgs/5.jpg', './imgs/6.jpg', './imgs/7.jpg',
    ]) {
        this.ele = document.createElement('ul');
        this.imgPathAry = imgPathAry;
    }

    decisionImgPath() { //static声明可以让所有的Uler类的实例共用一个内存地址，便于修改生成图片地址的规则
        const imgIndex = Math.round(Math.random() * (this.imgPathAry.length - 1));
        return this.imgPathAry[imgIndex];
    }

    grow() {
        const oneImage = new Imager(this.decisionImgPath());
        oneImage.init();
        this.ele.appendChild(oneImage.ele);
        oneImage.graduallyWakeIfMust();
        return oneImage;
    }
}

class FlowWater {
    constructor(rootEle,
                imgPathAry = [
                    './imgs/0.jpg', './imgs/1.jpg', './imgs/2.jpg', './imgs/3.jpg', './imgs/4.jpg', './imgs/5.jpg', './imgs/6.jpg', './imgs/7.jpg',
                ],
                column = 6,
                safeUlerRemainHeight = 400,
                everyTimeGrowAmount = 1,
                initImgAmountInEveryColumn = 3) {
        this.rootEle = rootEle;
        this.ulAry = [];
        this.imgPathAry = imgPathAry;
        this.column = column;
        this.safeUlerRemainHeight = safeUlerRemainHeight;
        this.everyTimeGrowAmount = everyTimeGrowAmount;
        this.initImgAmountInEveryColumn = initImgAmountInEveryColumn;
        this.antiTimer = null; //防抖定时器id,暂时赋值null,之后是定时器返回的数字
    }

    initUlersAry() {
        [...new Array(this.column).keys()].forEach((item, index) => {
            const oneUl = new Uler(this.imgPathAry);
            let fragment = document.createDocumentFragment();
            fragment.appendChild(oneUl.ele);
            this.rootEle.appendChild(fragment);
            fragment = null;
            this.ulAry.push(oneUl);
        })
    }

    growUlersInAry() {
        [...new Array(this.everyTimeGrowAmount).keys()].forEach((n, index) => {
            this.ulAry.forEach(item => {
                const oneImage = item.grow();
            });
        })
    }

    antiShake(fn, duration) { //防抖
        fn.call(this);
        this.antiTimer = window.setTimeout(fn => {
            if (this.antiTimer) {
                clearTimeout(this.antiTimer);
                return void 0;
            } else {
                fn.call(this);
            }
        }, duration);
    }

    listenWindowOnscroll() {
        window.addEventListener('scroll', () => {
            const bodyOffsetHeight = document.body.offsetHeight || document.documentElement.offsetHeight;
            const bodyScrollTop = document.body.scrollTop || document.documentElement.scrollTop;
            const shortestUler = this.ulAry.sort((a, b) => {
                return a.ele.offsetHeight - b.ele.offsetHeight
            })[0];
            const bottomPostion = shortestUler.ele.scrollTop + shortestUler.ele.offsetHeight;
            const safeBodyBottomPostion = bottomPostion - this.safeUlerRemainHeight;
            this.antiShake(()=>{
                if (bodyScrollTop + bodyOffsetHeight > safeBodyBottomPostion) {
                    shortestUler.grow();
                }
            }, 10000);
        }, false);
    }

    init() {
        this.initUlersAry();
        [...new Array(this.initImgAmountInEveryColumn).keys()].forEach((item, index) => {
            this.growUlersInAry();
        }); //先加载超过一屏幕的图片
        this.listenWindowOnscroll();
    }
}

const rootAry = [].slice.call(document.getElementsByClassName('flow-delay'));
rootAry.forEach(item => {
        const fl = new FlowWater(item)
        fl.init();
    }
);

